package com.crocodile.game17.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.crocodile.game17.common.AppException;
import com.crocodile.game17.common.AppExceptionMsgEnum;
import com.crocodile.game17.common.LoginUser;
import com.crocodile.game17.common.R;
import com.crocodile.game17.pojo.User;
import com.crocodile.game17.service.LoginService;
import com.crocodile.game17.util.JwtUtil;
import com.crocodile.game17.util.JwtUtilN;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * 登录验证
     * @param user
     * @return
     */
    public R<Map> login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //是否有用户
        if(ObjectUtil.isNull(authenticate)){
            throw new AppException(AppExceptionMsgEnum.NOT_FOUND);
        }
        //有用户
        LoginUser principal = (LoginUser) authenticate.getPrincipal();
        User backUser = principal.getUser();
        String userId = backUser.getId().toString();

        //jwt json web token封装
//        String token = JwtUtil.createJwt(userId);

        String token = JwtUtilN.createJwt(userId);

        HashMap<String,String> map = new HashMap<>();
        map.put("token",token);

        return R.success(map);
    }


}
